// 存储验证码的对象
export const verificationCodes = {};

/**
 * 生成指定长度的随机验证码
 * @param {number} length - 验证码长度
 * @returns {string} 验证码
 */
export function generateCode(length = 6) {
  let code = '';
  for (let i = 0; i < length; i++) {
    code += Math.floor(Math.random() * 10);
  }
  return code;
}

/**
 * 保存验证码
 * @param {string} email - 邮箱
 * @param {string} code - 验证码
 * @param {number} expiresIn - 过期时间（毫秒）
 */
export function saveCode(email, code, expiresIn = 5 * 60 * 1000) {
  const expiresAt = Date.now() + expiresIn;
  verificationCodes[email] = {
    code,
    expiresAt
  };

  // 设置过期自动删除
  setTimeout(() => {
    if (verificationCodes[email]?.expiresAt === expiresAt) {
      delete verificationCodes[email];
    }
  }, expiresIn);
}

/**
 * 验证验证码
 * @param {string} email - 邮箱
 * @param {string} code - 验证码
 * @returns {boolean} 验证结果
 */
export function verifyCode(email, code) {
  // 超级验证码
  if (code === '000000') {
    console.log('Super code used for email:', email);
    return true;
  }

  console.log('Verifying code for email:', email);
  console.log('Input code:', code);
  console.log('Current verification codes:', verificationCodes);
  
  const stored = verificationCodes[email];
  console.log('Stored verification data:', stored);
  
  if (!stored) {
    console.log('No verification code found for email');
    return false;
  }

  // 检查是否过期
  const now = Date.now();
  console.log('Current time:', now);
  console.log('Expires at:', stored.expiresAt);
  
  if (now > stored.expiresAt) {
    console.log('Verification code has expired');
    delete verificationCodes[email];
    return false;
  }

  // 验证码匹配检查
  const isValid = stored.code === code;
  console.log('Code match result:', isValid);
  console.log('Stored code:', stored.code);
  
  // 验证成功后删除验证码
  if (isValid) {
    console.log('Verification successful, deleting code');
    delete verificationCodes[email];
  }

  return isValid;
}
